/**
 * 留言板 create to by doujiabao - 20191023
 */

import React, { Component } from 'react'
import { Input, Button, message, Tooltip, Modal, Form, Icon, Row, Col, Switch } from 'antd'
import './index.css'
import moment from 'moment'
import http from '@/service/http/api'
import axios from 'axios'
import utils from '@/utils/index'
import cookie from '@/utils/cookie'

//pc背景
const pcBackground = 'http://www.005.tv/uploads/allimg/160929/143R32648-0.jpg'
//mobile背景
const mobileBackground = 'http://img1.imgtn.bdimg.com/it/u=2322914028,2251011611&fm=26&gp=0.jpg'
//登录表单
const LoginForm = Form.create()(class MessageBoard extends Component {

  state = {
    isLoading: false,
    // true登录 false注册
    formStatus: true
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({ isLoading: true })

        axios.get(http.login, {
          params: values
        }).then(res => {
          if (res.data.code === 200) {
            cookie.setCookie('account', res.data.data.user_account)

            message.success('登录成功')

            this.setState({
              isLoading: false
            }, () => {
              this.props.setUserInfo(res.data.data)
              this.props.escModal()
            })
          } else {
            this.setState({ isLoading: false })
            message.error('登录失败')
          }
        }).catch(err => {
          console.log(err)
        })
      }
    });
  }

  /**
   * 注册账号
   */
  register = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({ isLoading: true })

        axios.get(http.addUser, {
          params: values
        }).then(res => {
          if (res.data.code === 200) {
            this.setState({
              formStatus: true
            })
            message.success('注册成功，请登录')
          } else {
            message.error('注册失败')
          }
          this.setState({
            isLoading: false
          })
        }).catch(err => {
          console.log(err)
        })
      }
    });
  }

  render() {

    const { isLoading, formStatus } = this.state

    const { getFieldDecorator } = this.props.form

    return (<Form onSubmit={this.handleSubmit} className="login-form">
      <Form.Item>
        {getFieldDecorator('user_account', {
          rules: [{ required: true, message: '请输入账号' }],
        })(
          <Input
            prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
            placeholder="请输入账号"
          />,
        )}
      </Form.Item>
      {!formStatus ? <Form.Item>
        {getFieldDecorator('user_name', {
          rules: [{ required: true, message: '请输入名称' }],
        })(
          <Input
            prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
            placeholder="请输入名称"
          />,
        )}
      </Form.Item> : null}
      <Form.Item>
        <Row>
          <Col span={18}>
            <Switch checkedChildren="登录" unCheckedChildren="注册" defaultChecked checked={formStatus} onChange={(checked) => { this.setState({ formStatus: checked }) }} />
          </Col>
          <Col span={4}>
            {formStatus ? <Button type="primary" htmlType="submit" className="login-form-button" loading={isLoading}>登录</Button> : <Button type="primary" onClick={this.register} loading={isLoading}>注册</Button>}
          </Col>
        </Row>
      </Form.Item>
    </Form>)
  }

})

export default class MessageBoard extends Component {

  state = {
    //ws对象
    ws: {},
    //输入的消息
    iptVal: '',
    //发送状态
    isloading: false,
    //数据集
    dataMap: {},
    //ws对象data
    wsData: {},
    //登录状态
    isLogin: false,
    //登录modal
    loginVisible: false,
    //用户信息
    userInfo: {}
  }

  componentDidMount() {
    this.getUserInfo(cookie.getCookie('account'))

    // 打开一个WebSocket:
    var ws = new WebSocket('ws://39.106.181.25:9091')

    this.setState({ ws })

    // 响应onmessage事件:
    ws.onmessage = (msg) => {
      const wsData = JSON.parse(msg.data);

      this.loginStatus()

      this.setState({
        wsData: JSON.parse(msg.data)
      })

      wsData.code === 200 && this.getMessageList()
    };

    // 响应onclose事件:
    ws.onclose = (msg) => {
      cookie.removeCookie()
      this.setState({
        wsData: {
          code: 500,
          message: '已断开'
        }
      })
    };
  }

  /**
   * 登录状态
   */
  loginStatus = () => {
    this.setState({ isLogin: cookie.isLogin() })
  }

  /**
   * 信息窗置底
   */
  setScrollBottom = () => {
    this.pageMessageBoardMesList.scrollTop = this.pageMessageBoardMesList.scrollHeight
  }

  /**
   * 请求消息列表
   */
  getMessageList = () => {
    axios.get(http.getMessageList)
      .then((res) => {
        this.setState({
          dataMap: res.data
        }, () => {
          this.setScrollBottom()
        })
      })
      .catch((err) => {
        console.log(err);
      });
  }

  /**
     * 获取文本框内容
     */
  getIptVal = (el) => {
    this.setState({ iptVal: el.target.value })
  }

  /**
     * 发送
     */
  sendOut = () => {
    const { ws, iptVal, userInfo } = this.state

    if (iptVal) {

      this.setState({
        isloading: true
      })

      axios.get(http.addMessage, {
        params: {
          user_account: userInfo.user_account,
          user_name: userInfo.user_name,
          user_message: iptVal,
          send_time: moment().unix(),
        }
      }).then((res) => {
        this.setState({
          isloading: false,
          iptVal: ''
        }, () => {
          ws.send('客户端')
        })
      }).catch((err) => {
        this.setState({ isloading: false })
        message.error('发送失败')
      });

    } else {

      message.error('请输入消息')

    }

  }

  /**
   * 获取用户信息
   */
  getUserInfo = (account) => {

    axios.get(http.login, {
      params: { user_account: account }
    }).then(res => {
      if (res.data.code === 200) {
        this.setUserInfo(res.data.data)
      } else {
        message.error('获取用户信息失败')
      }
    }).catch(err => {
      console.log(err)
    })
  }

  /**
   * 设置用户信息
   */
  setUserInfo = (userInfo) => {
    if (userInfo) {
      this.setState({ userInfo }, () => {
        this.loginStatus()
      })
      message.success('您可以正常发送消息了')
    }
  }

  /**
   * 取消登录
   */
  handleCancel = () => {
    this.setState({ loginVisible: false })
  }

  render() {

    const {
      userInfo,
      dataMap,
      wsData,
      iptVal,
      isloading,
      isLogin,
      loginVisible,
    } = this.state

    const { data = [] } = dataMap;

    return (<div className='pageMessageBoard' style={{
      background: `url(${utils.isPc() ? pcBackground : mobileBackground}) #fff no-repeat center`,
      backgroundSize: 'cover'
    }}>

      <div className='pageMessageBoardWindow'>

        <div className={wsData.code === 200 ? 'pageMessageSuccess' : 'pageMessageErr'} >状态：<span>{wsData.message}</span>；当前连接数：<span>{wsData.connNum ? wsData.connNum : 0}</span>；</div>

        <div className='pageMessageBoardMesList' ref={el => this.pageMessageBoardMesList = el}>

          {
            data.map((itm, idx) => (<div key={idx} className='pageMessageBoardMesItem'>
              <div className={itm.user_account === userInfo.user_account ? 'isn' : ''} style={{ textAlign: itm.user_account === userInfo.user_account ? 'right' : 'left' }}>
                <div>{moment(+itm.send_time * 1000).format('YYYY-MM-DD hh:mm:ss')}</div>
                <div>{itm.user_account === userInfo.user_account && '*'}{itm.user_name}：</div>
                <label>{itm.user_message}</label>
              </div>
            </div>))
          }

        </div>

        <Tooltip title="登录方可发送消息" visible={!isLogin}>
          <div className='pageMessageBoardMesArea'>
            <Input onChange={this.getIptVal} value={iptVal} onPressEnter={this.sendOut} disabled={!isLogin} />
            &nbsp;
            {isLogin ? <Button type="primary" onClick={this.sendOut} loading={isloading} disabled={!isLogin}>发送</Button> : <Button type="primary" disabled={isLogin} onClick={() => this.setState({ loginVisible: true })}>登录</Button>}
          </div>
        </Tooltip>

      </div>

      <Modal
        title="登录"
        visible={loginVisible}
        maskClosable={false}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        width={360}
        okText='登录'
        cancelText='取消'
        footer={null}
      >
        <LoginForm
          escModal={this.handleCancel}
          setUserInfo={this.setUserInfo}
        />
      </Modal>

    </div >)

  }

}
